import { observable, action } from 'mobx';
import { WeaTableNew, WeaForm, WeaLogView } from 'comsMobx';
import * as Api from './../apis/fieldSetApi';
import { message } from 'antd';
import { WeaLocaleProvider } from 'ecCom';
import { affirmDeleted } from '../util/affirmDeleted';

const getLabel = WeaLocaleProvider.getLabel;
const { TableStore } = WeaTableNew;
const { LogStore } = WeaLogView;


class FieldSet {
  @observable form = new WeaForm();// 弹窗的form
  @observable searchForm = new WeaForm();// 搜索框的form
  @observable alertState = false;// 是否弹窗；
  @observable showButton = 1;// 显示弹窗button，1保存、2确定和取消
  @observable id = '';// 用来编辑字段
  // @observable selectedRowKeys = [];//用来编辑字段
  @observable mainTable = {
    tableStore: new TableStore(),
  }
  @observable rowDataInfo = []; // 选择行后存储每一行的数据
  @observable idArr = [];// 存储选中的行id
  @observable CanotClick = true;
  @observable key = '2';
  @observable logStore = new LogStore();// 日志store
  @observable showSearchAd = false;// 搜索框的下拉状态
  @observable logShow = false; // 日志弹窗是否显示
  // 存储保存添加字段
  @observable addfield = {
    showname: {},
    xml_name: {},
    descript: {},
    field_type: {},
    showorder: {},
  };
  @observable showDialogTitle = '0'// 弹窗显示标题 0代表新建字段 1代表编辑字段
  // 打开弹出窗口
  @action.bound newCreat () {
    this.showDialogTitle = '0';
    this.alertState = true;
    this.showButton = 1;
  }
  // 卸载组件状态
  @action
  setCanotClick = () => {
    this.CanotClick = true;
  }
  // 搜索
  @action.bound search () {
    this.getTableData(this.key);
  }
  @action showLog = () => {
    this.logShow = true;
  }
  @action setKey = (key) => {
    this.key = key;
  }
  // 添加或修改数据库字段
  @action.bound addField () {
    const formData = this.form.getFormParams();
    const params = {
      id: this.id,
      showname: formData.showname,
      xml_name: formData.xml_name,
      descript: formData.descript,
      showorder: formData.showorder,
      field_type: formData.field_type,
    };
    Api.addFiled(params).then((cb) => {
      if (cb.api_status) {
        this.CanotClick = true;
        this.getTableData(this.key);
        this.id = '';
        this.clearField();
        message.success(getLabel(30700, '操作成功!'));
      } else {
        message.error(cb.api_errormsg);
      }
      this.alertState = false;
    });
    this.form.resetForm();
  }
  // 获取列表数据
  @action.bound getTableData = () => {
    // this.key = key;
    this.idArr = [];
    const formData = this.searchForm.getFormParams();
    const params = {
      // key:key,
      showname: formData.showname || '',
      descript: formData.descript || '',
    };
    Api.getData(params).then((data) => {
      const { sessionkey } = data;
      if (sessionkey) {
        this.mainTable.tableStore.getDatas(sessionkey, 1);
        this.showSearchAd = false;
      }
    });
  }
  @action.bound setShowSearchAd () {
    this.showSearchAd = !this.showSearchAd;
  }
  // 清除存储的字段数据
  @action.bound clearField () {
    this.addfield.showorder = {};
    this.addfield.showname = {};
    this.addfield.xml_name = {};
    this.addfield.descript = {};
    this.addfield.field_type = {};
  }

  // 获取弹窗里表单数据
  @action.bound getFormContent () {
    let params = '';
    Api.tableContent(params).then((cb) => {
      let condition = [
        {
          title: '',
          items: cb.items,
          defaultshow: true,
        },
      ];
      this.form.setCondition(condition);
    });
  }

  // 关闭弹窗
  @action.bound onCancel () {
    this.alertState = false;
    this.clearField();
    this.form.resetForm();
    this.id = '';
  }
  // 选择行
  @action.bound onRowSelect (arr, arrInfoList) {
    this.idArr = arr;
    this.rowDataInfo = arrInfoList;
    this.checkMenuClick();
  }
  // 封存
  @action.bound onSeal () {
    if (this.idArr.length === 0) {
      return;
    }
    let id = [];
    for (let i = 0; i < this.idArr.length; i++) {
      if (this.idArr !== '') {
        id.push(this.idArr[i]);
      }
    }
    const params = { ids: id.join(',') };
    Api.onSeal(params).then((cb) => {
      if (cb.api_status) {
        message.success(getLabel('502844', '封存成功'));
        this.idArr = [];
        this.CanotClick = true;
        this.id = '';
      } else {
        message.error(getLabel(387615, '封存失败！'));
      }
      this.getTableData(this.key);
    });
  }

  // 解封
  @action.bound onUnseal () {
    if (this.idArr.length === 0) {
      return;
    }
    let id = [];
    for (let i = 0; i < this.idArr.length; i++) {
      if (this.idArr !== '') {
        id.push(this.idArr[i]);
      }
    }
    const params = { ids: id.join(',') };
    Api.onUnseal(params).then((cb) => {
      if (cb.api_status) {
        this.idArr = [];
        this.CanotClick = true;
        message.success(getLabel(22156, '解封成功！'));
      } else {
        message.error(getLabel(387617, '解封失败！'));
      }
      this.getTableData(this.key);
    });
  }

  // 删除
  @action.bound delete () {
    if (this.idArr.length === 0) {
      return;
    }
    let id = [];
    for (let i = 0; i < this.idArr.length; i++) {
      if (this.idArr !== '') {
        id.push(this.idArr[i]);
      }
    }
    const params = { ids: id.join(',') };
    Api.deleteList(params).then((cb) => {
      if (cb.api_status) {
        this.CanotClick = true;
        this.id = '';
        message.success(getLabel(83472, '删除成功！'));
      } else {
        message.error(getLabel(83473, '删除失败！'));
      }
      this.getTableData(this.key);
    });
  }
  // 获取搜索框的表单参数
  @action.bound getCondition () {
    const params = {};
    Api.getSearchCondion(params).then((cb) => {
      const condition = [
        {
          items: cb.items,
          defaultshow: true,
        },
      ];
      this.searchForm.setCondition(condition);
    });
  }
  // 对字段的操作
  @action.bound operate (record, index, operate, flag) {
    this.idArr = [record.id];
    this.id = record.id;
    switch (flag) {
      // 编辑
      /* eslint-disable */
      case '0':
        this.showDialogTitle = '1';
        this.showButton = 2;
        const params = {};
        this.alertState = true;
        Api.tableContent(params).then((cb) => {
          cb.items.map((item) => {
            for (let key in record) {
              if (key === item.domkey[0]) {
                item.value = record[key];
              }
            }
          });
          this.addfield.showname.value = record.showname;
          this.addfield.xml_name.value = record.xml_name;
          this.addfield.descript.value = record.descript;
          this.addfield.field_type.value = record.field_type;
          this.addfield.showorder.value = record.showorder;
          const condition = [
            {
              title: '',
              items: cb.items,
              defaultshow: true,
            },
          ];
          this.form.setCondition(condition);
          this.idArr = [];
        });
        /* eslint-enable */
        break;
      // 封存
      case '1':
        affirmDeleted(this.onSeal, { content: `${getLabel('521642', '确认要封存选中数据吗')}?` });
        break;
      // 解封
      case '2':
        affirmDeleted(this.onUnseal, { content: `${getLabel('521643', '确认要解封选中数据吗')}?` });
        break;
      // 删除
      case '3':
        affirmDeleted(() => this.delete(), { onCancel: () => this.setMobxState({ idArr: [] }) });
        break;
      case '4':
        this.targetId = record.id;
        this.logShow = true;
        break;
    }
  }

  // 新建字段校验
  @action onCheck () {
    const formData = this.form.getFormParams();
    const reg = /^\d+/;
    this.form.validateForm().then((f) => {
      if (f.isValid) {
        if (reg.test(formData.xml_name)) {
          message.warning(getLabel(514524, '数据库字段名不能以数字开头，请重新输入！'));
        } else {
          this.addField();
        }
      } else {
        f.showErrors();
      }
    });
  }
  // 判断批量处理按钮是否可以点击
  @action.bound checkMenuClick () {
    if (this.idArr.length > 0) {
      switch (this.key) {
        case '1': {
          this.CanotClick = false;
          break;
        }
        case '2': {
          for (let arrInfo of this.rowDataInfo) {
            if (arrInfo.iscancel === '1') {
              this.CanotClick = true;
              return;
            }
            this.CanotClick = false;
          }
          break;
        }
        case '3': {
          for (let arrInfo of this.rowDataInfo) {
            if (arrInfo.iscancel === '0') {
              this.CanotClick = true;
              return;
            }
          }
          this.CanotClick = false;
          break;
        }
      }
    } else {
      this.CanotClick = true;
    }
  }

  @action.bound
  setMobxState (params) {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  }
}

export default new FieldSet();
